package com.vhly.classfile;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;

public class InnerClasses
        implements Attribute {

    private Vector<InnerClass> inners;
    private int inners_count;
    private int name_index;
    private int data_len;

    public InnerClasses() {
        name_index = 0;
        data_len = 2;
        inners_count = 0;
        inners = new Vector<InnerClass>();
    }

    public void setNameIndex(int i) {
        name_index = i;
    }

    public int getNameIndex() {
        return name_index;
    }

    public void setDataLen(int i) {
        data_len = i;
    }

    public int getDataLen() {
        return data_len;
    }

    public void read(DataInputStream din, boolean flag)
            throws IOException {
        if (flag)
            name_index = din.readUnsignedShort();
        data_len = din.readInt();
        inners_count = din.readUnsignedShort();
        for (int i = 0; i < inners_count; i++) {
            InnerClass innerclass = new InnerClass();
            innerclass.read(din);
            inners.add(innerclass);
        }

    }

    public void write(DataOutputStream dout)
            throws IOException {
        dout.writeShort(name_index);
        dout.writeInt(data_len);
        dout.writeShort(inners_count);
        for (int i = 0; i < inners_count; i++) {
            InnerClass innerclass = inners.elementAt(i);
            innerclass.write(dout);
        }

    }

    public int getType() {
        return 6;
    }

    public Enumeration getInnerClasses() {
        return inners.elements();
    }

    public int size() {
        return inners.size();
    }

    public InnerClass getInnerClassAt(int index) {
        int in = 0;
        if (inners.isEmpty())
            return null;
        if (index < 0)
            in = 0;
        if (index >= inners.size())
            in = inners.size() - 1;
        return inners.elementAt(in);
    }

    public void addInnerClass(InnerClass ic) {
        if (ic != null) {
            inners.add(ic);
            data_len += 8;
            inners_count = inners.size();
        }
    }
}